<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>座位管理-图书馆座位预约管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
        }

        /* 左侧导航栏样式 */
        .sidebar {
            width: 250px;
            background: #1a2a6c;
            color: white;
            height: 100vh;
            position: fixed;
            overflow-y: auto;
            transition: width 0.3s ease;
        }

        .sidebar.collapsed {
            width: 70px;
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.2rem;
            font-weight: bold;
            white-space: nowrap;
            overflow: hidden;
        }

        .logo i {
            font-size: 1.5rem;
            min-width: 24px;
        }

        .sidebar-nav ul {
            list-style: none;
            padding: 0;
        }

        .nav-item {
            margin: 5px 0;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 20px;
            color: white;
            text-decoration: none;
            transition: background-color 0.3s;
            white-space: nowrap;
            overflow: hidden;
        }

        .nav-link:hover, .nav-item.active .nav-link {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .nav-link i {
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            display: flex;
            flex-direction: column;
            transition: margin-left 0.3s ease;
        }

        .main-content.expanded {
            margin-left: 70px;
        }

        /* 顶部导航栏 */
        .top-navbar {
            background-color: white;
            padding: 15px 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .navbar-left {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .menu-toggle {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #1a2a6c;
            padding: 5px;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .menu-toggle:hover {
            background-color: #f0f0f0;
        }

        .page-title {
            color: #1a2a6c;
            font-size: 1.5rem;
        }

        .navbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            padding: 8px 35px 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 250px;
        }

        .search-box i {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #888;
        }

        .user-profile {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .user-profile img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            background-color: #1a73e8;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
        }

        /* 座位管理内容区域 */
        .seat-management {
            padding: 25px;
            flex: 1;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .filter-container {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .filter-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .filter-item label {
            font-weight: 500;
            white-space: nowrap;
        }

        .form-control {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-width: 150px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            font-weight: 500;
            transition: all 0.3s;
        }

        .btn-primary {
            background: #1a73e8;
            color: white;
        }

        .btn-primary:hover {
            background: #0d62d9;
        }

        .btn-outline {
            background: transparent;
            border: 1px solid #1a73e8;
            color: #1a73e8;
        }

        .btn-outline:hover {
            background: #1a73e8;
            color: white;
        }

        .btn-success {
            background: #2ecc71;
            color: white;
        }

        .btn-success:hover {
            background: #27ae60;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 14px;
        }

        /* 卡片样式 */
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 25px;
        }

        .card-header {
            padding: 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 18px;
            font-weight: 600;
            color: #1a2a6c;
        }

        .table-info {
            color: #7f8c8d;
            font-size: 14px;
        }

        .table-container {
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }

        .data-table th {
            background: #1a2a6c;
            color: white;
            font-weight: 600;
        }

        .data-table tr:hover {
            background: #f8f9fa;
        }

        .status {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .status.available {
            background: rgba(46, 204, 113, 0.2);
            color: #27ae60;
        }

        .status.occupied {
            background: rgba(241, 196, 15, 0.2);
            color: #f39c12;
        }

        .status.in-use {
            background: rgba(243, 156, 18, 0.2);
            color: #d35400;
        }

        .status.temporarily-leaving {
            background: rgba(52, 152, 219, 0.2);
            color: #2980b9;
        }

        .status.selected {
            background: rgba(155, 89, 182, 0.2);
            color: #8e44ad;
        }

        .status.maintenance {
            background: rgba(149, 165, 166, 0.2);
            color: #7f8c8d;
        }

        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            margin: 0 2px;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .action-btn.view {
            color: #3498db;
        }

        .action-btn.view:hover {
            background: rgba(52, 152, 219, 0.1);
        }

        .action-btn.edit {
            color: #2ecc71;
        }

        .action-btn.edit:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .action-btn.delete {
            color: #e74c3c;
        }

        .action-btn.delete:hover {
            background: rgba(231, 76, 60, 0.1);
        }

        .card-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .pagination ul {
            display: flex;
            list-style: none;
            gap: 5px;
        }

        .pagination a {
            display: block;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #1a73e8;
            transition: all 0.3s;
        }

        .pagination a.active, .pagination a:hover {
            background: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }

        .pagination a.disabled {
            color: #ccc;
            cursor: not-allowed;
            pointer-events: none;
        }

        .map-controls {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .map-placeholder {
            padding: 40px;
            text-align: center;
            color: #7f8c8d;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            z-index: 1000;
            overflow: auto;
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 0;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            animation: modalFade 0.3s;
        }

        @keyframes modalFade {
            from {opacity: 0; transform: translateY(-50px);}
            to {opacity: 1; transform: translateY(0);}
        }

        .modal-header {
            background: #1a2a6c;
            color: white;
            padding: 20px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
        }

        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: white;
        }

        .close-btn:hover {
            color: #ddd;
        }

        .modal-body {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #1a2a6c;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-row .form-group {
            flex: 1;
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .batch-actions {
            padding: 15px 20px;
            background: #f8f9fa;
            border-bottom: 1px solid #eee;
            display: none;
        }

        .batch-actions.show {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .selected-count {
            font-weight: 500;
            color: #1a2a6c;
        }

        /* 加载指示器 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 100;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 70px;
            }

            .sidebar:not(.collapsed) .logo span,
            .sidebar:not(.collapsed) .nav-link span {
                display: none;
            }

            .main-content {
                margin-left: 70px;
            }

            .toolbar {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-container {
                width: 100%;
            }

            .action-buttons {
                width: 100%;
                justify-content: flex-start;
            }

            .form-row {
                flex-direction: column;
                gap: 0;
            }
        }
    </style>
</head>
<body>
<!-- 左侧导航栏 -->
<aside class="sidebar">
    <div class="sidebar-header">
        <h1 class="logo">
            <span>图书馆座位预约管理系统</span>
        </h1>
    </div>
    <nav class="sidebar-nav">
        <ul>
            <li class="nav-item">
                <a href="index.html" class="nav-link">
                    <i class="fa fa-home"></i>
                    <span>首页</span>
                </a>
            </li>
            <li class="nav-item active">
                <a href="seat-management1.html" class="nav-link">
                    <i class="fa fa-th-large"></i>
                    <span>座位管理</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="booking-management.html" class="nav-link">
                    <i class="fa fa-calendar-check-o"></i>
                    <span>预约管理</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="user-management1.html" class="nav-link">
                    <i class="fa fa-users"></i>
                    <span>用户管理</span>
                </a>
            </li>
        </ul>
    </nav>
</aside>

<!-- 主内容区域 -->
<div class="main-content">
    <!-- 顶部导航栏 -->
    <header class="top-navbar">
        <div class="navbar-left">
            <button class="menu-toggle" id="menuToggle">
                <i class="fa fa-bars"></i>
            </button>
            <h2 class="page-title">座位管理</h2>
        </div>
        <div class="navbar-right">
            <div class="search-box">
                <input type="text" placeholder="搜索座位..." id="searchInput">
                <i class="fa fa-search"></i>
            </div>
            <div class="user-profile">
                <img src="manager.png" alt="管理员头像">
                <span>管理员</span>
            </div>
        </div>
    </header>

    <div class="seat-management">
        <div class="toolbar">
            <div class="filter-container">
                <div class="filter-item">
                    <label>楼层:</label>
                    <select class="form-control" id="floorFilter">
                        <option value="all">全部楼层</option>
                        <option value="1">1楼-阅览区</option>
                        <option value="2">2楼-电子阅览区</option>
                        <option value="3">3楼-考公考研区</option>
                        <option value="4">4楼-阅读区</option>
                        <option value="5">5楼-讨论区</option>
                    </select>
                </div>
                <div class="filter-item">
                    <label>状态:</label>
                    <select class="form-control" id="statusFilter">
                        <option value="all">全部状态</option>
                        <option value="AVAILABLE">可预约</option>
                        <option value="RESERVED">已被预约</option>
                        <option value="OCCUPIED">使用中</option>
                        <option value="AWAY">暂离中</option>
                    </select>
                </div>
            </div>
            <div class="action-buttons">
                <button class="btn btn-primary" id="addSeatBtn">
                    <i class="fa fa-plus"></i> 新增座位
                </button>
                <button class="btn btn-outline" id="refreshBtn">
                    <i class="fa fa-refresh"></i> 刷新
                </button>
            </div>
        </div>
        <div class="batch-actions" id="batchActions">
            <div class="selected-count" id="selectedCount">已选择 0 项</div>
            <button class="btn btn-outline btn-sm" id="batchEnableBtn">
                <i class="fa fa-check"></i> 批量启用
            </button>
            <button class="btn btn-outline btn-sm" id="batchDisableBtn">
                <i class="fa fa-times"></i> 批量禁用
            </button>
            <button class="btn btn-danger btn-sm" id="batchDeleteBtn">
                <i class="fa fa-trash"></i> 批量删除
            </button>
        </div>

        <!-- 座位列表 -->
        <div class="card" id="seatListCard">
            <div class="card-header">
                <h3>座位列表</h3>
                <div class="table-info">
                    <span id="tableInfo">共 0 个座位</span>
                </div>
            </div>
            <div class="table-container">
                <table class="data-table" id="seatTable">
                    <thead>
                    <tr>

                        <th>座位ID</th>
                        <th>座位号</th>
                        <th>楼层</th>
                        <th>座位类型</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="seatTableBody">
                    </tbody>
                </table>
            </div>
            <div class="card-footer">
                <div class="pagination">
                    <ul id="paginationList">
                    </ul>
                </div>
            </div>
        </div>
        <div class="card">
            <div class="card-body">
            </div>
        </div>
    </div>
</div>

<!-- 模态框 -->
<div class="modal" id="seatModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">新增座位</h3>
            <button class="close-btn" id="closeModal">&times;</button>
        </div>
        <div class="modal-body">
            <form id="seatForm">
                <div class="form-row">
                    <div class="form-group">
                        <label for="seatNumber">座位号</label>
                        <input type="text" id="seatNumber" required>
                    </div>
                    <div class="form-group">
                        <label for="floor">楼层</label>
                        <select id="floor" required>
                            <option value="">请选择楼层</option>
                            <option value="1">1楼-阅览区</option>
                            <option value="2">2楼-电子阅览区</option>
                            <option value="3">3楼-考公考研区</option>
                            <option value="4">4楼-阅读区</option>
                            <option value="5">5楼-讨论区</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label for="seatType">座位类型</label>
                    <select id="seatType" required>
                        <option value="normal">普通座位</option>
                        <option value="computer">电脑座位</option>
                        <option value="discussion">讨论区座位</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="status">状态</label>
                    <select id="status" required>
                        <option value="AVAILABLE">可预约</option>
                        <option value="RESERVED">已被预约</option>
                        <option value="OCCUPIED">使用中</option>
                        <option value="AWAY">暂离中</option>
                    </select>
                </div>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancelBtn">取消</button>
            <button class="btn btn-primary" id="saveBtn">
                <span id="saveBtnText">保存</span>
                <div class="loading" id="saveBtnLoading" style="display: none;"></div>
            </button>
        </div>
    </div>
</div>

<div class="modal" id="deleteModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>确认删除</h3>
            <button class="close-btn" id="closeDeleteModal">&times;</button>
        </div>
        <div class="modal-body">
            <p id="deleteMessage">确定要删除这个座位吗？此操作不可撤销。</p>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancelDeleteBtn">取消</button>
            <button class="btn btn-danger" id="confirmDeleteBtn">
                <span id="deleteBtnText">确认删除</span>
                <div class="loading" id="deleteBtnLoading" style="display: none;"></div>
            </button>
        </div>
    </div>
</div>

<script>

    const API_BASE_URL = 'http://localhost:8080/api/seat';
    // 后端API调用
    const api = {
        // 获取座位列表 - 调用真实后端接口
        async getSeats() {
            try {
                const response = await fetch(`${API_BASE_URL}/status`);
                if (!response.ok) {
                    throw new Error('获取座位数据失败');
                }
                const seats = await response.json();
                return seats;
            } catch (error) {
                console.error('API调用失败:', error);
                // 如果API调用失败，使用默认数据作为fallback
                return this.getDefaultSeats();
            }
        },

        // 默认座位数据（仅作为fallback）
        getDefaultSeats() {
            return [
                {
                    id: 1,
                    floorAreaId: 1,
                    seatNumber: "1A01",
                    seatType: "normal",
                    baseStatus: "AVAILABLE",
                    createdAt: "2025-10-30 10:12:41",
                    updatedAt: null
                },
                {
                    id: 2,
                    floorAreaId: 1,
                    seatNumber: "1A02",
                    seatType: "normal",
                    baseStatus: "RESERVED",
                    createdAt: "2025-10-30 10:12:41",
                    updatedAt: null
                },
                {
                    id: 3,
                    floorAreaId: 2,
                    seatNumber: "2B01",
                    seatType: "computer",
                    baseStatus: "IN_USE",
                    createdAt: "2025-10-30 10:12:41",
                    updatedAt: null
                }
            ];
        },

        // 添加座位 - 调用后端API
        async addSeat(seatData) {
            try {
                const response = await fetch(`${API_BASE_URL}/add`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        seatNumber: seatData.seatNumber,
                        floorAreaId: parseInt(seatData.floor),
                        seatType: seatData.seatType,
                        baseStatus: seatData.status
                    })
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(errorText || '添加座位失败');
                }

                const newSeat = await response.json();
                return newSeat;
            } catch (error) {
                console.error('添加座位失败:', error);
                throw error;
            }
        },

        // 更新座位 - 调用后端API
        async updateSeat(id, seatData) {
            try {
                const response = await fetch(`${API_BASE_URL}/${id}`, {
                    method: 'PATCH',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        seatNumber: seatData.seatNumber,
                        floorAreaId: parseInt(seatData.floor),
                        seatType: seatData.seatType,
                        baseStatus: seatData.status
                    })
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(errorText || '更新座位失败');
                }

                const updatedSeat = await response.json();
                return updatedSeat;
            } catch (error) {
                console.error('更新座位失败:', error);
                throw error;
            }
        },

        // 删除座位 - 调用后端API
        async deleteSeat(id) {
            try {
                const response = await fetch(`${API_BASE_URL}/${id}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(errorText || '删除座位失败');
                }

                return { success: true, message: '删除成功' };
            } catch (error) {
                console.error('删除座位失败:', error);
                throw error;
            }
        },

        // 批量修改座位状态 - 调用后端API
        async batchUpdateSeats(ids, updates) {
            try {
                const requests = ids.map(id =>
                    fetch(`${API_BASE_URL}/${id}`, {
                        method: 'PATCH',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            baseStatus: updates.baseStatus
                        })
                    })
                );

                const responses = await Promise.all(requests);
                const errors = [];

                responses.forEach((response, index) => {
                    if (!response.ok) {
                        errors.push(`座位 ${ids[index]} 更新失败`);
                    }
                });

                if (errors.length > 0) {
                    throw new Error(errors.join(', '));
                }

                return { success: true, updatedCount: ids.length };
            } catch (error) {
                console.error('批量更新失败:', error);
                throw error;
            }
        },

        // 批量删除座位 - 调用后端API
        async batchDeleteSeats(ids) {
            try {
                const requests = ids.map(id =>
                    fetch(`${API_BASE_URL}/${id}`, {
                        method: 'DELETE'
                    })
                );

                const responses = await Promise.all(requests);
                const errors = [];

                responses.forEach((response, index) => {
                    if (!response.ok) {
                        errors.push(`座位 ${ids[index]} 删除失败`);
                    }
                });

                if (errors.length > 0) {
                    throw new Error(errors.join(', '));
                }

                return { success: true, deletedCount: ids.length };
            } catch (error) {
                console.error('批量删除失败:', error);
                throw error;
            }
        }
    };

    // 工具函数：根据楼层ID获取楼层名称
    function getFloorName(floorAreaId) {
        const floorMap = {
            1: '1楼-阅览区',
            2: '2楼-电子阅览区',
            3: '3楼-考公考研区',
            4: '4楼-阅读区',
            5: '5楼-讨论区'
        };
        return floorMap[floorAreaId] || `${floorAreaId}楼`;
    }

    // 工具函数：根据状态值获取状态文本和样式
    function getStatusInfo(baseStatus) {
        const statusMap = {
            'AVAILABLE': { text: '可预约', class: 'available' },
            'RESERVED': { text: '已被预约', class: 'occupied' },
            'OCCUPIED': { text: '使用中', class: 'in-use' },
            'AWAY': { text: '暂离中', class: 'temporarily-leaving' },
            'SELECTED': { text: '已选择', class: 'selected' }
        };
        return statusMap[baseStatus] || { text: '未知', class: 'available' };
    }

    // 工具函数：获取座位类型文本
    function getSeatTypeText(seatType) {
        const typeMap = {
            'normal': '普通座位',
            'computer': '电脑座位',
            'discussion': '讨论区座位'
        };
        return typeMap[seatType] || seatType;
    }

    // DOM元素
    const seatTableBody = document.getElementById('seatTableBody');
    const seatModal = document.getElementById('seatModal');
    const deleteModal = document.getElementById('deleteModal');
    const seatForm = document.getElementById('seatForm');
    const addSeatBtn = document.getElementById('addSeatBtn');
    const saveBtn = document.getElementById('saveBtn');
    const saveBtnText = document.getElementById('saveBtnText');
    const saveBtnLoading = document.getElementById('saveBtnLoading');
    const closeModal = document.getElementById('closeModal');
    const cancelBtn = document.getElementById('cancelBtn');
    const closeDeleteModal = document.getElementById('closeDeleteModal');
    const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
    const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
    const deleteBtnText = document.getElementById('deleteBtnText');
    const deleteBtnLoading = document.getElementById('deleteBtnLoading');
    const searchInput = document.getElementById('searchInput');
    const floorFilter = document.getElementById('floorFilter');
    const statusFilter = document.getElementById('statusFilter');
    const selectAll = document.getElementById('selectAll');
    const batchActions = document.getElementById('batchActions');
    const selectedCount = document.getElementById('selectedCount');
    const batchEnableBtn = document.getElementById('batchEnableBtn');
    const batchDisableBtn = document.getElementById('batchDisableBtn');
    const batchDeleteBtn = document.getElementById('batchDeleteBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const paginationList = document.getElementById('paginationList');
    const tableInfo = document.getElementById('tableInfo');
    const seatListCard = document.getElementById('seatListCard');

    // 分页相关变量
    let currentPage = 1;
    const itemsPerPage = 10;
    let filteredSeats = [];
    let allSeats = [];

    // 当前编辑的座位ID
    let currentEditId = null;
    let currentDeleteId = null;
    let selectedSeats = new Set();

    // 初始化页面
    document.addEventListener('DOMContentLoaded', function() {
        loadSeats();
        setupEventListeners();

        // 菜单切换功能
        const menuToggle = document.getElementById('menuToggle');
        const sidebar = document.querySelector('.sidebar');
        const mainContent = document.querySelector('.main-content');

        if (menuToggle) {
            menuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('collapsed');
                mainContent.classList.toggle('expanded');
            });
        }
    });

    // 加载座位数据
    async function loadSeats() {
        showLoading();
        try {
            allSeats = await api.getSeats();
            filterSeats();
        } catch (error) {
            console.error('加载座位数据失败:', error);
            alert('加载座位数据失败，请刷新页面重试');
        } finally {
            hideLoading();
        }
    }

    // 显示加载状态
    function showLoading() {
        if (!document.getElementById('loadingOverlay')) {
            const overlay = document.createElement('div');
            overlay.id = 'loadingOverlay';
            overlay.className = 'loading-overlay';
            overlay.innerHTML = '<div class="loading"></div>';
            seatListCard.style.position = 'relative';
            seatListCard.appendChild(overlay);
        }
    }

    // 隐藏加载状态
    function hideLoading() {
        const overlay = document.getElementById('loadingOverlay');
        if (overlay) {
            overlay.remove();
        }
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 模态框控制
        addSeatBtn.addEventListener('click', openAddModal);
        closeModal.addEventListener('click', closeSeatModal);
        cancelBtn.addEventListener('click', closeSeatModal);
        saveBtn.addEventListener('click', saveSeat);

        // 删除模态框控制
        closeDeleteModal.addEventListener('click', closeDeleteModalFunc);
        cancelDeleteBtn.addEventListener('click', closeDeleteModalFunc);
        confirmDeleteBtn.addEventListener('click', confirmDelete);

        // 筛选和搜索
        searchInput.addEventListener('input', filterSeats);
        floorFilter.addEventListener('change', filterSeats);
        statusFilter.addEventListener('change', filterSeats);

        // 批量操作
        selectAll.addEventListener('change', toggleSelectAll);
        batchEnableBtn.addEventListener('click', batchEnable);
        batchDisableBtn.addEventListener('click', batchDisable);
        batchDeleteBtn.addEventListener('click', batchDelete);

        // 其他按钮
        refreshBtn.addEventListener('click', refreshData);
    }

    // 渲染座位列表
    function renderSeats() {
        seatTableBody.innerHTML = '';

        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = startIndex + itemsPerPage;
        const currentSeats = filteredSeats.slice(startIndex, endIndex);

        if (currentSeats.length === 0) {
            seatTableBody.innerHTML = `
                <tr>
                    <td colspan="7" style="text-align: center; padding: 30px;">
                        <i class="fa fa-inbox" style="font-size: 48px; color: #ddd; margin-bottom: 10px;"></i>
                        <p>暂无座位数据</p>
                        <p class="no-data-hint" style="color: #7f8c8d; font-size: 14px; margin-top: 10px;">
                            尝试调整筛选条件
                        </p>
                    </td>
                </tr>
            `;
            return;
        }

        currentSeats.forEach(seat => {
            const row = document.createElement('tr');
            const isSelected = selectedSeats.has(seat.id);
            const statusInfo = getStatusInfo(seat.baseStatus);

            row.innerHTML = `

                <td>${seat.id}</td>
                <td>${seat.seatNumber}</td>
                <td>${getFloorName(seat.floorAreaId)}</td>
                <td>${getSeatTypeText(seat.seatType)}</td>
                <td><span class="status ${statusInfo.class}">${statusInfo.text}</span></td>
                <td>
                    <button class="action-btn view" data-id="${seat.id}">
                        <i class="fa fa-eye"></i>
                    </button>
                    <button class="action-btn edit" data-id="${seat.id}">
                        <i class="fa fa-edit"></i>
                    </button>
                    <button class="action-btn delete" data-id="${seat.id}">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            `;

            seatTableBody.appendChild(row);
        });

        // 更新表格信息
        tableInfo.textContent = `共 ${filteredSeats.length} 个座位，显示第 ${startIndex + 1}-${Math.min(endIndex, filteredSeats.length)} 个`;

        // 添加行内按钮事件监听器
        addRowEventListeners();
    }

    // 更新分页
    function updatePagination() {
        paginationList.innerHTML = '';

        const totalPages = Math.ceil(filteredSeats.length / itemsPerPage);

        // 上一页按钮
        const prevLi = document.createElement('li');
        prevLi.innerHTML = `<a href="#" id="prevPage" class="${currentPage === 1 ? 'disabled' : ''}">上一页</a>`;
        paginationList.appendChild(prevLi);

        // 页码按钮
        const maxVisiblePages = 5;
        let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
        let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

        // 调整起始页码，确保显示maxVisiblePages个页码
        if (endPage - startPage + 1 < maxVisiblePages) {
            startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }

        // 第一页和省略号
        if (startPage > 1) {
            const firstLi = document.createElement('li');
            firstLi.innerHTML = `<a href="#" data-page="1">1</a>`;
            paginationList.appendChild(firstLi);

            if (startPage > 2) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.innerHTML = `<a href="#" class="disabled">...</a>`;
                paginationList.appendChild(ellipsisLi);
            }
        }

        // 页码
        for (let i = startPage; i <= endPage; i++) {
            const pageLi = document.createElement('li');
            pageLi.innerHTML = `<a href="#" data-page="${i}" class="${i === currentPage ? 'active' : ''}">${i}</a>`;
            paginationList.appendChild(pageLi);
        }

        // 最后一页和省略号
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                const ellipsisLi = document.createElement('li');
                ellipsisLi.innerHTML = `<a href="#" class="disabled">...</a>`;
                paginationList.appendChild(ellipsisLi);
            }

            const lastLi = document.createElement('li');
            lastLi.innerHTML = `<a href="#" data-page="${totalPages}">${totalPages}</a>`;
            paginationList.appendChild(lastLi);
        }

        // 下一页按钮
        const nextLi = document.createElement('li');
        nextLi.innerHTML = `<a href="#" id="nextPage" class="${currentPage === totalPages ? 'disabled' : ''}">下一页</a>`;
        paginationList.appendChild(nextLi);

        // 添加分页事件监听器
        addPaginationEventListeners();
    }

    // 添加分页事件监听器
    function addPaginationEventListeners() {
        // 上一页
        document.getElementById('prevPage')?.addEventListener('click', function(e) {
            e.preventDefault();
            if (currentPage > 1) {
                currentPage--;
                renderSeats();
                updatePagination();
            }
        });

        // 下一页
        document.getElementById('nextPage')?.addEventListener('click', function(e) {
            e.preventDefault();
            const totalPages = Math.ceil(filteredSeats.length / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderSeats();
                updatePagination();
            }
        });

        // 页码
        document.querySelectorAll('[data-page]').forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                if (!this.classList.contains('disabled')) {
                    const page = parseInt(this.getAttribute('data-page'));
                    if (page !== currentPage) {
                        currentPage = page;
                        renderSeats();
                        updatePagination();
                    }
                }
            });
        });
    }

    // 添加行内按钮事件监听器
    function addRowEventListeners() {
        // 查看按钮
        document.querySelectorAll('.action-btn.view').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                viewSeat(id);
            });
        });

        // 编辑按钮
        document.querySelectorAll('.action-btn.edit').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                editSeat(id);
            });
        });

        // 删除按钮
        document.querySelectorAll('.action-btn.delete').forEach(btn => {
            btn.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                deleteSeat(id);
            });
        });

        // 行选择复选框
        document.querySelectorAll('.row-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const id = this.getAttribute('data-id');
                if (this.checked) {
                    selectedSeats.add(id);
                } else {
                    selectedSeats.delete(id);
                    selectAll.checked = false;
                }
                updateBatchActions();
            });
        });
    }

    // 打开新增座位模态框
    function openAddModal() {
        document.getElementById('modalTitle').textContent = '新增座位';
        seatForm.reset();
        currentEditId = null;
        seatModal.classList.add('show');
    }

    // 查看座位详情
    function viewSeat(id) {
        const seat = allSeats.find(s => s.id == id);
        if (seat) {
            const statusInfo = getStatusInfo(seat.baseStatus);
            alert(`座位详情:\n座位ID: ${seat.id}\n座位号: ${seat.seatNumber}\n楼层: ${getFloorName(seat.floorAreaId)}\n座位类型: ${getSeatTypeText(seat.seatType)}\n状态: ${statusInfo.text}\n创建时间: ${seat.createdAt}`);
        }
    }

    // 编辑座位
    function editSeat(id) {
        const seat = allSeats.find(s => s.id == id);
        if (seat) {
            document.getElementById('modalTitle').textContent = '编辑座位';
            document.getElementById('seatNumber').value = seat.seatNumber;
            document.getElementById('floor').value = seat.floorAreaId.toString();
            document.getElementById('seatType').value = seat.seatType;
            document.getElementById('status').value = seat.baseStatus;

            currentEditId = id;
            seatModal.classList.add('show');
        }
    }

    // 删除座位
    function deleteSeat(id) {
        currentDeleteId = id;
        const seat = allSeats.find(s => s.id == id);
        if (seat) {
            document.getElementById('deleteMessage').textContent =
                `确定要删除座位 ${seat.seatNumber} 吗？此操作不可撤销。`;
            deleteModal.classList.add('show');
        }
    }

    // 保存座位（新增或编辑）
    async function saveSeat() {
        const seatNumber = document.getElementById('seatNumber').value;
        const floor = document.getElementById('floor').value;
        const seatType = document.getElementById('seatType').value;
        const status = document.getElementById('status').value;

        if (!seatNumber || !floor) {
            alert('请填写所有必填字段');
            return;
        }

        // 显示加载状态
        saveBtnText.style.display = 'none';
        saveBtnLoading.style.display = 'inline-block';
        saveBtn.disabled = true;

        try {
            if (currentEditId) {
                // 编辑现有座位
                await api.updateSeat(currentEditId, {
                    seatNumber,
                    floor,
                    seatType,
                    status
                });
            } else {
                // 新增座位
                await api.addSeat({
                    seatNumber,
                    floor,
                    seatType,
                    status
                });
            }

            closeSeatModal();
            await loadSeats();
            alert(currentEditId ? '座位已更新' : '座位已添加');
        } catch (error) {
            console.error('保存座位失败:', error);
            alert(`操作失败: ${error.message}`);
        } finally {
            // 恢复按钮状态
            saveBtnText.style.display = 'inline-block';
            saveBtnLoading.style.display = 'none';
            saveBtn.disabled = false;
        }
    }

    // 关闭座位模态框
    function closeSeatModal() {
        seatModal.classList.remove('show');
    }

    // 关闭删除确认模态框
    function closeDeleteModalFunc() {
        deleteModal.classList.remove('show');
    }

    // 确认删除
    async function confirmDelete() {
        if (!currentDeleteId) return;

        // 显示加载状态
        deleteBtnText.style.display = 'none';
        deleteBtnLoading.style.display = 'inline-block';
        confirmDeleteBtn.disabled = true;

        try {
            await api.deleteSeat(currentDeleteId);
            selectedSeats.delete(currentDeleteId);
            closeDeleteModalFunc();
            await loadSeats();
            alert('座位已删除');
        } catch (error) {
            console.error('删除座位失败:', error);
            alert(`删除失败: ${error.message}`);
        } finally {
            // 恢复按钮状态
            deleteBtnText.style.display = 'inline-block';
            deleteBtnLoading.style.display = 'none';
            confirmDeleteBtn.disabled = false;
            currentDeleteId = null;
        }
    }

    // 筛选座位
    function filterSeats() {
        const searchTerm = searchInput.value.toLowerCase();
        const floorValue = floorFilter.value;
        const statusValue = statusFilter.value;

        filteredSeats = allSeats.filter(seat => {
            // 搜索条件
            const matchesSearch = !searchTerm ||
                seat.seatNumber.toLowerCase().includes(searchTerm) ||
                seat.id.toString().includes(searchTerm);

            // 楼层条件
            const matchesFloor = floorValue === 'all' || seat.floorAreaId.toString() === floorValue;

            // 状态条件
            const matchesStatus = statusValue === 'all' || seat.baseStatus === statusValue;

            return matchesSearch && matchesFloor && matchesStatus;
        });

        // 重置到第一页
        currentPage = 1;
        renderSeats();
        updatePagination();
    }

    // 全选/取消全选
    function toggleSelectAll() {
        const checkboxes = document.querySelectorAll('.row-checkbox');
        if (selectAll.checked) {
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
                const id = checkbox.getAttribute('data-id');
                selectedSeats.add(id);
            });
        } else {
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                const id = checkbox.getAttribute('data-id');
                selectedSeats.delete(id);
            });
        }
        updateBatchActions();
    }

    // 更新批量操作栏
    function updateBatchActions() {
        const count = selectedSeats.size;
        selectedCount.textContent = `已选择 ${count} 项`;

        if (count > 0) {
            batchActions.classList.add('show');
        } else {
            batchActions.classList.remove('show');
        }
    }

    // 批量启用
    async function batchEnable() {
        if (selectedSeats.size === 0) {
            alert('请先选择要操作的座位');
            return;
        }

        if (confirm(`确定要启用 ${selectedSeats.size} 个座位吗？`)) {
            try {
                await api.batchUpdateSeats(Array.from(selectedSeats), { baseStatus: 'AVAILABLE' });
                selectedSeats.clear();
                await loadSeats();
                alert('已启用选中的座位');
            } catch (error) {
                console.error('批量启用失败:', error);
                alert(`操作失败: ${error.message}`);
            }
        }
    }

    // 批量禁用
    async function batchDisable() {
        if (selectedSeats.size === 0) {
            alert('请先选择要操作的座位');
            return;
        }

        if (confirm(`确定要禁用 ${selectedSeats.size} 个座位吗？`)) {
            try {
                await api.batchUpdateSeats(Array.from(selectedSeats), { baseStatus: 'RESERVED' });
                selectedSeats.clear();
                await loadSeats();
                alert('已禁用选中的座位');
            } catch (error) {
                console.error('批量禁用失败:', error);
                alert(`操作失败: ${error.message}`);
            }
        }
    }

    // 批量删除
    async function batchDelete() {
        if (selectedSeats.size === 0) {
            alert('请先选择要删除的座位');
            return;
        }

        if (confirm(`确定要删除 ${selectedSeats.size} 个座位吗？此操作不可撤销。`)) {
            try {
                await api.batchDeleteSeats(Array.from(selectedSeats));
                selectedSeats.clear();
                await loadSeats();
                alert('已删除选中的座位');
            } catch (error) {
                console.error('批量删除失败:', error);
                alert(`操作失败: ${error.message}`);
            }
        }
    }


    // 刷新数据
    async function refreshData() {
        await loadSeats();
        alert('数据已刷新');
    }
</script>
</body>
</html>